<?php
use app\library\model\Medoo;

class BaseModel
{
    protected $db;

    protected $table;

    protected $principal = 'id';

    public function __construct()
    {
        $this->db = Medoo::getInstance();
    }

    protected function get($join = null, $colimns = null, $where = null) {
        return $this->db->get($this->table, $join, $colimns, $where);
    }

    protected function select($join, $columns = null, $where = null){
        $table = $this->table;
        if (isset($join['as'])) {
            if (!empty($join['as'])) {
                $table .= "({$join['as']})";
            }
            unset($join['as']);
        }
        return $this->db->select($table, $join, $columns, $where);
    }

    public function insert($datas, $id = false){
        return $this->db->insert($this->table, $datas , $id);
    }

    protected function update($data, $where = null){
        return $this->db->update($this->table, $data, $where);
    }

    protected function delete($where){
        return $this->db->delete($this->table, $where);
    }

    public function count(array $join, $column = null, $where = null)
    {
        return $this->db->count($this->table, $join, $column, $where);
    }


    public function find($id, $columns = '*') {
        return $this->get($columns, [$this->principal => $id]);
    }

    public function updateById($data, $id){
        return $this->update($data,[$this->principal => $id]);
    }

    protected function deleteById($id) {
        return $this->delete([$this->principal => $id]);
    }

    public function findAll($where = null, $columns = '*') {
        return $this->select($columns, $where);
    }

    public function findList($where = null, $colums = null, $page = 1, $pagesize = 10, $join = null){
        $where['LIMIT'] = [($page-1) * $pagesize, $pagesize];
        if ($join === null) {
            $res = $this->select($colums, $where);
        } else {
            $res = $this->select($join, $colums, $where);
        }
        return $res;
    }

    public function last(){
        return $this->db->last();
    }

}